package com.example.SocialApplication.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;

import com.example.SocialApplication.Daemon;
import com.example.SocialApplication.R;
import com.example.SocialApplication.activity.dialog.VkDialogLogout;
import com.example.SocialApplication.db.entity.User;
import com.example.SocialApplication.service.CallServiceAddFacebookUser;
import com.example.SocialApplication.service.CallServiceAddVkUser;
import com.example.SocialApplication.service.GetBitmapFromStream;
import com.example.SocialApplication.social.facebook.AsyncFacebookRunner;
import com.example.SocialApplication.social.facebook.DialogError;
import com.example.SocialApplication.social.facebook.Facebook;
import com.example.SocialApplication.social.facebook.FacebookError;
import com.example.SocialApplication.social.facebook.SessionStore;
import com.example.SocialApplication.social.vk.Vkontakte;
import com.example.SocialApplication.social.vk.service.GetVkUserAvatar;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

public class LoginActivity extends Activity implements Vkontakte.VkontakteListener, VkDialogLogout.VkDialogLogoutListener {
    public static final String APP_ID = "262675760538442"; //the API Key for your Facebook APPs

    private final int REQUEST_LOGIN = 1;
    public static String API_ID = "3692076";

    private User user;
    private Vkontakte vk;

    private Facebook mFacebook;
    private String SHARED_PREFERENCE = "facebookSharedPref";
    private SharedPreferences sharedPreferences;
    private VkDialogLogout vkDialogLogout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_layout);

        vk = Vkontakte.getInstance(this);
        vk.setListener(this);
    }

    public void loginVK(View v) {
        if (vk.isAuthorized()) {
            vkDialogLogout = new VkDialogLogout(this, this);
            vkDialogLogout.show();
        } else {
            vk.showLoginDialog();
        }
    }

    public void facebookLogin(View v) {
        sharedPreferences = getSharedPreferences(SHARED_PREFERENCE, 0);

        try {
            mFacebook = new Facebook(APP_ID);

            final AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(mFacebook);

            mFacebook.authorize(this, new String[]{"email", "read_stream", "user_hometown", "user_location", "friends_about_me", "friends_hometown", "friends_location", "user_relationships", "friends_relationship_details", "friends_birthday", "friends_education_history", "friends_website"}, -1, new Facebook.DialogListener() {
                public void onComplete(Bundle values) {
                    final String access_token = values.getString("facebook_access_token");
                    new GetHttpTask() {
                        @Override
                        protected void onPostExecute(Object s) {
                            JSONObject jObj = null;
                            try {
                                jObj = new JSONObject(s.toString());
                                user = new User();
                                user.setSocialId(jObj.getString("id"));
                                user.setFirstName(jObj.getString("first_name"));
                                user.setLastName(jObj.getString("last_name"));
                                new GetBitmapFromStream(){
                                    @Override
                                    protected void onPostExecute(Bitmap bitmap) {
                                        if(bitmap != null) {
                                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                            bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                                            byte[] b = baos.toByteArray();
                                            String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
                                            user.setPhoto(imageEncoded);

                                            finishFacebookLogin();
                                        }
                                    }
                                }.execute(String.valueOf(jObj.getJSONObject("picture").getJSONObject("data").get("url")));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            SharedPreferences.Editor editor = sharedPreferences.edit();
                            editor.putString("facebook_access_token", access_token);
                            editor.commit();

                            //mAsyncRunner.request("me/friends", new FriendsRequestListener());
                        }
                    }.execute(null);
                }

                public void onFacebookError(FacebookError error) {
                    Log.i("public void onFacebookError(FacebookError error)....", "....");
                }

                public void onError(DialogError e) {
                    Log.i("public void onError(DialogError e)....", "....");
                            /*CustomConfirmOkDialog dialog = new CustomConfirmOkDialog(FacebookList.this, R.style.CustomDialogTheme, Utils.FACEBOOK_CONNECTION_ERROR);
                            dialog.show();*/
                }

                public void onCancel() {
                    Log.i("public void onCancel()....", "....");
                }
            });

            SessionStore.restore(mFacebook, this);
//                    SessionEvents.addAuthListener(new SampleAuthListener());
//                    SessionEvents.addLogoutListener(new SampleLogoutListener());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void finishFacebookLogin() {
        new CallServiceAddFacebookUser(user) {
            @Override
            protected void onPostExecute(Integer integer) {
//                if(integer != 0) {
                Daemon.add("user", user);
                Daemon.add("login", "facebook");
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                intent.putExtra("user", user);
                startActivity(intent);
                finish();
            }
        }.execute();
    }

    private void finishLogin() {

//        new GetVkFriends() {
//            @Override
//            protected void onPostExecute(Void aVoid) {
//                super.onPostExecute(aVoid);
//            }
//        }.execute("https://api.vkontakte.ru/method/friends.get?uid="+vk.get_userId()+"&order=name&fields=photo_100");

        Daemon.add("user", user);
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        intent.putExtra("user", user);
        startActivity(intent);
        finish();
    }

    @Override
    public void onContinue() {
        onLoginComplete("");
        vkDialogLogout.dismiss();
        vkDialogLogout = null;
    }

    @Override
    public void onCancel() {
        vk.logOut();
        vk.showLoginDialog();
        vkDialogLogout.dismiss();
        vkDialogLogout = null;
    }

    private class GetHttpTask extends AsyncTask {
        @Override
        protected Object doInBackground(Object... params) {
            String result = "";
            try {
                String mAccessToken = mFacebook.getAccessToken();
                HttpClient httpclient = new DefaultHttpClient();

                HttpGet httpget = new HttpGet("https://graph.facebook.com/me?access_token=" + mAccessToken + "&fields=id,first_name,last_name,location,picture");
                HttpResponse response;
                response = httpclient.execute(httpget);
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result = EntityUtils.toString(entity);
                    //parseJSON(result);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }
    }

    public class FriendsRequestListener implements
            AsyncFacebookRunner.RequestListener {

        /**
         * Called when the request to get friends has been completed.
         * Retrieve and parse and display the JSON stream.
         */
        public void onComplete(final String response) {
            try {
                // process the response here: executed in background thread
                Log.d("Facebook-Example-Friends Request", "response.length(): " +
                        response.length());
                Log.d("Facebook-Example-Friends Request", "Response: " + response);

                final JSONObject json = new JSONObject(response);
                JSONArray d = json.getJSONArray("data");
                int l = (d != null ? d.length() : 0);
                Log.d("Facebook-Example-Friends Request", "d.length(): " + l);

                for (int i = 0; i < l; i++) {
                    JSONObject o = d.getJSONObject(i);
                    String n = o.getString("name");
                    String id = o.getString("id");
                    System.out.print("");
                }

                // Only the original owner thread can touch its views

            } catch (JSONException e) {
                Log.w("Facebook-Example", "JSON Error in response");
            }
        }

        @Override
        public void onIOException(IOException e) {

        }

        @Override
        public void onFileNotFoundException(FileNotFoundException e) {

        }

        @Override
        public void onMalformedURLException(MalformedURLException e) {

        }

        @Override
        public void onFacebookError(FacebookError e) {

        }
    }

    @Override
    public void onPostComplete(String result) {
        // TODO Auto-generated method stub
        @SuppressWarnings("unused")
        String r = result;
    }

    @Override
    public void onPostError(String result) {
        // TODO Auto-generated method stub
        @SuppressWarnings("unused")
        String r = result;
    }

    @Override
    public void onLoginComplete(String result) {
        // TODO Auto-generated method stub
        @SuppressWarnings("unused")
        String r = result;
        new GetVkUserAvatar() {
            @Override
            protected void onPostExecute(String result) {
//                LoginActivity.this.user = user;
                try {
                    JSONArray array = new JSONObject(result).getJSONArray("response");
                    JSONObject jObj = array.getJSONObject(0);

                    user = new User();
                    user.setSocialId(jObj.getString("uid"));
                    user.setFirstName(jObj.getString("first_name"));
                    user.setLastName(jObj.getString("last_name"));
                    new GetBitmapFromStream() {
                        @Override
                        protected void onPostExecute(Bitmap bitmap) {
                            if (bitmap != null) {
                                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                                byte[] b = baos.toByteArray();
                                String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
                                user.setPhoto(imageEncoded);

                                finishVkLogin();
                            }
                        }
                    }.execute(jObj.getString("photo_100"));

//                    try {
//                        InputStream is = (InputStream) new URL(jObj.getString("photo")).getContent();
//                        user.setPhoto(BitmapFactory.decodeStream(is));
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
                } catch (Exception e) {
                    Log.i("Exception1 is Here>> ", e.toString());
                    e.printStackTrace();
                }
            }
        }.execute(vk.getUserUrl());
    }

    private void finishVkLogin() {
        new CallServiceAddVkUser(user) {
            @Override
            protected void onPostExecute(Integer integer) {
//                if(integer != 0) {
                Daemon.add("user", user);
                Daemon.add("login", "vk");
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                intent.putExtra("user", user);
                startActivity(intent);
                finish();
            }
        }.execute();
    }

    @Override
    public void onLoginError(String result) {
        // TODO Auto-generated method stub
        @SuppressWarnings("unused")
        String r = result;
    }

    @Override
    public void didEndGettingUserInfo(String result) {
        // TODO Auto-generated method stub
        @SuppressWarnings("unused")
        String r = result;
    }
}
